<?php

namespace App\Http\Controllers\Api;

use Cache;
use App\Http\Requests\Api\CaptchaRequest;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;

class CaptchasController extends Controller
{
    public function store(CaptchaRequest $request, CaptchaBuilder $captchaBuilder)
    {
        $key = 'captcha-' . str_random(15);
        $phone = $request->phone;

        $captcha = $captchaBuilder->build();
        $expiredAt = now()->addMinutes(2);

        Cache::put($key, [
            'phone' => $phone,
            'code' => $captcha->getPhrase()
        ], $expiredAt);

        $result = [
            'captcha_key' => $key,
            'expired_at' => $expiredAt->toDateTimeString(),
            'captcha_image_content' => $captcha->inline(),
        ];

        return $this->response->array($result)->setStatusCode(201);
    }

    public function checkCaptcha(Request $request)
    {
        $captchaKey = $request->captcha_key;
        $captchaData = Cache::get($captchaKey);
        if (!$captchaData){
            return $this->response->err  or('图片验证码已失效');
        }

        if (hash_equals($captchaData['code'], $request->captcha_code)){
            // 验证码错误就清除缓存
            Cache::forget($captchaKey);
            return $this->response->errorUnauthorized('验证码错误');
        }
    }
}
